#include"head.h"
#define N 3

int pipearr[2];
//注册信号函数
void signal_get(int num)
{
    if(num==2)
    {
        printf("\nget 2th signal\n");
        write(pipearr[1],"1",1);
    }
}
int main()
{
    //注册2号信号
    int ret = pipe(pipearr);
    ERROR_CHECK(ret,-1,"pipe");

    //新建子进程
    struct work_status workarr[N];

    init_pool(workarr,N);
    for(int i =0 ;i<N;i++)
    {
        printf("main.c:local_socket:%d\n",workarr[i].local_socket);
    }

    //进行三次挥手并且监听

    char* ip ="192.168.237.128";
    char* port = "8080";

    int socket_fd=socket(AF_INET,SOCK_STREAM,0);
    ERROR_CHECK(socket_fd,-1,"socket");

    printf("socket_fd:main.c:%d\n",socket_fd);


    start_listen(socket_fd,ip,port);

    //设置监听，陆续将socket_fd和子进程的未满信息和信号注册信息入队列
    int epfd=epoll_create(1);
    ERROR_CHECK(epfd,-1,"epoll_create");

    add_epoll(epfd,socket_fd);
    signal(2,signal_get);

    add_epoll(epfd,pipearr[0]);

    for(int i=0;i<N;i++)
    {
        add_epoll(epfd,workarr[i].local_socket);
    }


    while(1)
    {

        struct epoll_event event[1024];
        int ready_num = epoll_wait(epfd,event,1024,-1);
        //ERROR_CHECK(ready_num,-1,"epoll_wait");

        for(int j=0;j<ready_num;j++)
        {
            int fd = event[j].data.fd;
            printf("\n\nmain.c:socket_fd:%d-fd:%d\n",socket_fd,fd);
            if(fd==pipearr[0])
            {
                char buffer[10];
                read(pipearr[0],buffer,sizeof(buffer));
                //给进程发送要赴死的标志
                for(int k = 0;k < N;k++)
                {
                    give_son_do(2,workarr,N,-1);
                }
                //等待所有进程完结
                for(int k = 0; k < N ;k++)
                {
                    pid_t close_pid=wait(NULL);
                    printf("main.c:closed:pid:%d\n",close_pid);
                }
                printf("进程退出\n");
                exit(0);
            }
            else
            {
                if(fd == socket_fd)
                {
                    printf("something happen\n");
                    int net_fd =accept(fd,NULL,NULL);
                    printf("net_fd:main.c:%d\n",net_fd);
                    ERROR_CHECK(net_fd,-1,"accept");

                    //把任务分发给子进程完成
                    give_son_do(net_fd,workarr,N,0);
                    close(net_fd);
                }
                else 
                {
                    //第三钟情况收到来自子进程的信息
                    char buf[10];
                    ret = recv(fd,buf,sizeof(buf),0);
                    ERROR_CHECK(ret,-1,"recv");

                    printf("main.c:busy to free:%s\n",buf);

                    for(int k=0;k<N;k++)
                    {
                        if(workarr[k].local_socket==fd)
                        {
                            workarr[k].status=FREE;
                            break;
                        }
                    }
                }
            }
        }
    }
    return 0;
}







